from app import db
from datetime import datetime

class DataSource(db.Model):
    """数据源模型"""
    __tablename__ = 'datasources'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False, unique=True)
    type = db.Column(db.String(50), nullable=False, default='mysql')  # 数据源类型，目前只支持mysql
    host = db.Column(db.String(255), nullable=False)
    port = db.Column(db.Integer, nullable=False)
    username = db.Column(db.String(100), nullable=False)
    password = db.Column(db.String(255), nullable=False)
    database = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text)
    status = db.Column(db.String(20), default='unknown')  # 连接状态：connected, disconnected, unknown
    last_test_time = db.Column(db.DateTime)  # 最后测试时间
    created_at = db.Column(db.DateTime, default=datetime.now)
    updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
    
    # 关联的同步任务（作为源数据源）
    source_tasks = db.relationship('SyncTask', foreign_keys='SyncTask.source_id', backref='source_datasource', lazy='dynamic')
    # 关联的同步任务（作为目标数据源）
    target_tasks = db.relationship('SyncTask', foreign_keys='SyncTask.target_id', backref='target_datasource', lazy='dynamic')
    
    def __repr__(self):
        return f'<DataSource {self.name}>'
    
    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'type': self.type,
            'host': self.host,
            'port': self.port,
            'username': self.username,
            'database': self.database,
            'description': self.description,
            'status': self.status,
            'last_test_time': self.last_test_time.strftime('%Y-%m-%d %H:%M:%S') if self.last_test_time else None,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S')
        }